﻿using DocumentFormat.OpenXml.Wordprocessing;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using NP.BPMReportPlatform.DBHelper;
using NP.BPMReportPlatform.Entities.NIP_Wechat;
using NP.BPMReportPlatform.Entities.NIP_WorkFlow;
using NP.Enterprise.Utils.Http;
using Org.BouncyCastle.Bcpg;
using Serilog;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Threading.Tasks;

namespace NP.BPMReportPlatform.RecurringJobs
{
    /// <summary>
    /// 待办中心相关接口服务
    /// </summary>
    public class NIP_WechatRecurringJob : BpmReportPlatformRecurringJob, INIP_WechatRecurringJob
    {
        private readonly SqlSugarClient _dbNIPWechat, _dbNIPWorkFlow;
        private readonly ILogger _logger;
        private readonly INPRestHttpHelper _nPRestHttp;
        private readonly IConfiguration _configuration;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="sqlSugarAppService"></param>
        /// <param name="logger"></param>
        public NIP_WechatRecurringJob(ISqlSugarAppService sqlSugarAppService, ILogger logger, INPRestHttpHelper nPRestHttp,
            IConfiguration configuration)
        {
            _dbNIPWechat = sqlSugarAppService.GetNIP_WechatInstance();
            _dbNIPWorkFlow = sqlSugarAppService.GetNIPWolkFlowInstance();
            _logger = logger;
            _nPRestHttp = nPRestHttp;
            _configuration = configuration;
        }

        /// <summary>
        /// 清理已审批的待办
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task ClearApprovedToDoList()
        {
            var statusArray = new string[] { "撤回","撤消","单据撤回","关闭","拒绝","删除", "审批拒绝","审批通过",
            "审批退回","退回","完成","已撤回","已撤销","已关闭","已解决","已拒绝","已取消","已删除",
            "已审批","已完成","已作废","直接结束","自动关闭","作废","重新制单","作业完成"};

            var updateObj = await _dbNIPWechat.Queryable<WechatFlowInst>().InnerJoin<WechatJobList>((wf, wj) => wf.ID.Equals(wj.FlowInstID)).With(SqlWith.NoLock).
                Where((wf, wj) => wj.STATUS == 0 && SqlFunc.ContainsArray(statusArray, wf.STATUS)).
                Select((wf, wj) => new WechatJobList() { ID = wj.ID, STATUS = 4 }).ToListAsync();

            var rst = await _dbNIPWechat.Updateable(updateObj).UpdateColumns(wj => wj.STATUS).
                WhereColumns(wj => wj.ID).ExecuteCommandAsync();
        }

        /// <summary>
        /// 定时推送
        /// </summary>
        /// <returns></returns>
        public async Task PushWechat()
        {
            try
            {
                var pushDataCount = _dbNIPWorkFlow.Queryable<PendingList>()
                    .Where(x => x.Attr1 == "WECHAT" && x.Status == 0).Count();
                var headers = new Dictionary<string, string>
                {
                    { "Content-Type", "application/json" },
                    { "requestId", Guid.NewGuid().ToString() },
                    { "trackId", Guid.NewGuid().ToString() },
                    { "sourceSystem", "BPMNEW" },
                    { "serviceName", "S_XXX_BPM_WechatPushServices_S" }
                };

                if (pushDataCount > 0)
                {
                    var sendData = new
                    {
                        Root = new ESBRoot(),
                        DoPush = new
                        {
                            i = pushDataCount,
                        }
                    };
                    var result = await _nPRestHttp.ESBPostAsync(_configuration["Nippon:ESB:ESB_API_SERVICE_COMM"], JsonConvert.SerializeObject(sendData), headers);
                }
            }
            catch (Exception ex)
            {
                _logger.Error("PushWechat:" + ex.Message);
            }
        }
    }

    public class ESBRoot
    {
        /// <summary>
        /// SpaceUrl
        /// </summary>
        [JsonProperty(PropertyName = "space-url")]
        public string SpaceUrl => "http://tempuri.org/";

        /// <summary>
        /// SpaceName
        /// </summary>
        [JsonProperty(PropertyName = "space-name")]
        public string SpaceName => "tem";

        /// <summary>
        /// SpaceEle
        /// </summary>
        [JsonProperty(PropertyName = "space-ele")]
        public string SpaceEle => "true";
    }
}
